package StudyCode.summary.zipfile;

import java.io.*;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DownloadFileFromURLAndUnzip {
	public static void downloadFileInto(CharSequence stringURL, File directory) {
		try {
			URL url = new URL(stringURL.toString());
			unzipIntoDirectory(url.openStream(), directory);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void unzipIntoDirectory(File file, File directory) {
		try {
			unzipIntoDirectory(new FileInputStream(file), directory);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static void unzipIntoDirectory(InputStream inputStream,
	                                      File directory) {
		if (directory.isFile())
			return;
		directory.mkdirs();

		try {
			inputStream = new BufferedInputStream(inputStream);
			inputStream = new ZipInputStream(inputStream);

			for (ZipEntry entry = null; (entry = ((ZipInputStream) inputStream)
					.getNextEntry()) != null; ) {
				StringBuilder pathBuilder = new StringBuilder(
						directory.getPath()).append('/').append(
						entry.getName());
				File file = new File(pathBuilder.toString());

				if (entry.isDirectory()) {
					file.mkdirs();
					continue;
				}

//				StreamUtil.write(pathBuilder, inputStream, false);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
//			StreamUtil.closeQuietly(inputStream);
		}
	}
}
